package com.example.edu_service.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.edu_service.entity.EduChapter;
import com.example.edu_service.entity.EduVideo;
import com.example.edu_service.entity.chapter.Chapter;
import com.example.edu_service.entity.chapter.Video;
import com.example.edu_service.mapper.EduChapterMapper;
import com.example.edu_service.service.EduChapterService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.edu_service.service.EduVideoService;
import com.example.servicebase.exceptionhandler.ZDYException;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 课程 服务实现类
 * </p>
 *
 * @author testjava
 * @since 2021-08-02
 */
@Service
public class EduChapterServiceImpl extends ServiceImpl<EduChapterMapper, EduChapter> implements EduChapterService {


    @Autowired
    private EduVideoService videoService;
    @Override
    public List<Chapter> getChapterById(String courseId) {

        QueryWrapper<EduChapter> wrapperChapter=new QueryWrapper<>();
        wrapperChapter.eq("course_id",courseId);
        List<EduChapter> chapterList = baseMapper.selectList(wrapperChapter);


        QueryWrapper<EduVideo> wrapperVideo=new QueryWrapper<>();
        wrapperVideo.eq("course_id",courseId);
        List<EduVideo> videoList = videoService.list(wrapperVideo);


        List<Chapter> list=new ArrayList<>();

        for (int i = 0; i < chapterList.size(); i++) {

            EduChapter eduChapter = chapterList.get(i);
            Chapter chapter = new Chapter();
            BeanUtils.copyProperties(eduChapter,chapter);

            list.add(chapter);

            List<Video> videos= new ArrayList<>();

            for (int i1 = 0; i1 < videoList.size(); i1++) {

                EduVideo eduVideo = videoList.get(i1);

                if (eduVideo.getChapterId().equals(eduChapter.getId())){

                    Video video = new Video();
                    BeanUtils.copyProperties(eduVideo,video);
                    videos.add(video);

                }

            }

            chapter.setChildren(videos);


        }

        return list;
    }

    @Override
    public Boolean deleteChapter(String chapterId) {
        QueryWrapper<EduVideo> wrapper=new QueryWrapper<>();
        wrapper.eq("chapter_id",chapterId);

        int count = videoService.count(wrapper);

        if (count > 0){
            throw new ZDYException(20001,"不能删除");
        }else {
            int result = baseMapper.deleteById(chapterId);
            return result>0;
        }

    }

    @Override
    public void removeChapterById(String courseId) {
        QueryWrapper<EduChapter> wrapper = new QueryWrapper<>();
        wrapper.eq("course_id",courseId);
        baseMapper.delete(wrapper);
    }




}
